package com.abc.recycling.service.impl;

import com.abc.recycling.mapper.UserMapper;
import com.abc.recycling.model.User;
import com.abc.recycling.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class UserServiceImpl implements UserService, UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        
        return new org.springframework.security.core.userdetails.User(
            user.getUsername(),
            user.getPassword(),
            user.getStatus() == 1,
            true,
            true,
            true,
            Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + user.getRole()))
        );
    }

    @Override
    public List<User> findResidents(String keyword) {
        return userMapper.findByRoleAndKeywordWithoutPaging("RESIDENT", keyword);
    }

    @Override
    public User findById(Long id) {
        User user = userMapper.findById(id);
        if (user != null && "COLLECTOR".equals(user.getRole())) {
            // 使用新的查询方法获取带统计数据的回收员信息
            user = userMapper.findCollectorWithStats(id);
        }
        return user;
    }

    @Override
    @Transactional
    public void create(User user) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(user.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setStatus(1); // 默认启用
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        
        userMapper.insert(user);
    }

    @Override
    @Transactional
    public void update(User user) {
        User existingUser = findById(user.getId());
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }

        // 如果修改了用户名，检查新用户名是否已存在
        if (!existingUser.getUsername().equals(user.getUsername()) &&
            userMapper.findByUsername(user.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 如果是回收员，保留原有的统计数据和其他字段
        if ("COLLECTOR".equals(user.getRole())) {
            user.setAverageRating(existingUser.getAverageRating());
            user.setTotalOrders(existingUser.getTotalOrders());
            user.setMonthlyOrders(existingUser.getMonthlyOrders());
            user.setMonthlyIncome(existingUser.getMonthlyIncome());
            // 如果没有设置服务区域，使用原有的或默认值
            if (user.getServiceArea() == null) {
                user.setServiceArea(existingUser.getServiceArea() != null ? 
                    existingUser.getServiceArea() : "未设置");
            }
        }

        // 如果提供了新密码则加密，否则使用原密码
        if (StringUtils.hasText(user.getPassword())) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        } else {
            user.setPassword(existingUser.getPassword());
        }

        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    @Transactional
    public void updateStatus(Long id, Integer status) {
        User user = new User();
        user.setId(id);
        user.setStatus(status);
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateStatus(user);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    @Transactional
    public User register(User user) {
        // 检查用户名是否已存在
        if (existsByUsername(user.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查手机号是否已存在
        if (existsByPhone(user.getPhone())) {
            throw new RuntimeException("手机号已被注册");
        }
        
        // 检查邮箱是否已存在
        if (existsByEmail(user.getEmail())) {
            throw new RuntimeException("邮箱已被注册");
        }
        
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setStatus(1); // 默认启用
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        
        userMapper.insert(user);
        return user;
    }

    @Override
    public User login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        
        if (user.getStatus() != 1) {
            throw new RuntimeException("账号已被禁用");
        }
        
        return user;
    }

    @Override
    @Transactional
    public User updateUser(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
        return user;
    }

    @Override
    @Transactional
    public void updateAvatar(User user) {
        User existingUser = userMapper.findById(user.getId());
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }
        
        existingUser.setAvatar(user.getAvatar());
        existingUser.setUpdateTime(LocalDateTime.now());
        userMapper.update(existingUser);
    }

    @Override
    @Transactional
    public void changePassword(Long userId, String oldPassword, String newPassword) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            throw new RuntimeException("原密码错误");
        }
        
        user.setPassword(passwordEncoder.encode(newPassword));
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    @Transactional
    public void updatePassword(User user) {
        User existingUser = userMapper.findById(user.getId());
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }
        
        existingUser.setPassword(passwordEncoder.encode(user.getPassword()));
        existingUser.setUpdateTime(LocalDateTime.now());
        userMapper.update(existingUser);
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.findById(id);
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public List<User> getUsersByRole(String role) {
        return userMapper.findByRole(role);
    }

    @Override
    public List<User> searchUsers(String role, String keyword) {
        return userMapper.findByRoleAndKeywordWithoutPaging(role, keyword);
    }

    @Override
    @Transactional
    public void updateUserStatus(Long userId, Integer status) {
        User user = new User();
        user.setId(userId);
        user.setStatus(status);
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateStatus(user);
    }

    @Override
    @Transactional
    public void deleteUser(Long userId) {
        userMapper.deleteById(userId);
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public long countActiveUsers() {
        // 获取当月第一天
        LocalDateTime monthStart = LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth())
                .withHour(0).withMinute(0).withSecond(0);
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        
        // 统计本月有订单的用户数量
        Integer count = userMapper.countActiveUsersByDateRange(monthStart, now);
        return count != null ? count : 0L;
    }

    @Override
    @Transactional
    public User createUser(User user) {
        if ("COLLECTOR".equals(user.getRole())) {
            user.setAverageRating(0.0);
            user.setTotalOrders(0L);
            user.setMonthlyOrders(0L);
            user.setMonthlyIncome(0.0);
            if (user.getServiceArea() == null) {
                user.setServiceArea("未设置");
            }
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setStatus(1);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);
        return user;
    }

    @Override
    public Page<User> findByRoleAndKeyword(String role, String keyword, Pageable pageable) {
        return userMapper.findByRoleAndKeyword(role, keyword, pageable);
    }

    @Override
    public boolean existsByUsername(String username) {
        return userMapper.findByUsername(username) != null;
    }

    @Override
    public boolean existsByPhone(String phone) {
        return userMapper.findByPhone(phone) != null;
    }

    @Override
    public boolean existsByEmail(String email) {
        return userMapper.findByEmail(email) != null;
    }

    @Override
    public List<User> findCollectors(String keyword) {
        List<User> collectors = userMapper.findByRoleAndKeywordWithoutPaging("COLLECTOR", keyword);
        // 为每个回收员获取统计数据
        for (User collector : collectors) {
            User collectorWithStats = userMapper.findCollectorWithStats(collector.getId());
            if (collectorWithStats != null) {
                collector.setAverageRating(collectorWithStats.getAverageRating());
                collector.setTotalOrders(collectorWithStats.getTotalOrders());
                collector.setMonthlyOrders(collectorWithStats.getMonthlyOrders());
                collector.setMonthlyIncome(collectorWithStats.getMonthlyIncome());
            }
        }
        return collectors;
    }
} 